#include <QDebug>
#include <QFile>
#include <QRegExp>

QString readFile(QString path){
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return "";

    QString data = QString(file.readAll());
    file.close();
    return data;
}

bool writeCSVFile(QString path, QString data){
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QStringList list = data.split("\n");
    QTextStream out(&file);
    out.setCodec("GB2312");

    foreach(QString line, list){
        QStringList lines = line.split(" ");
        QString str;
        foreach(QString sline, lines){
            if(sline.trimmed().isEmpty()) continue;
            str += sline.trimmed()+",";
        }
//        qInfo()<<str;
        out << str << "\n";
    }
    out.flush();

    file.close();
}

void handleFile(QString path)
{
    QString data = readFile(path);
//    qInfo()<<data;
    if(data.isEmpty()){
        qInfo()<<"输入文件内容为空";
        return;
    }
    bool result = writeCSVFile("data.csv", data);
    if(!result){
        qInfo()<<"csv文件写入失败";
    }
}

/*
自定义脚本，快速处理文本，按照空格，切分为excel表格数据
输入 data.txt
输出 data.csv
*/
int main(int argc, char *argv[])
{
    if(argc >= 2){
        qInfo()<<"处理文件中 "<<argv[1];
        handleFile(argv[1]);
    }
    else{
        qInfo()<<"请输入要处理的文件.";
    }
    qInfo()<<"程序结束";
    return 0;
}
